package by.giava.mytrips.test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TreeSet;

import org.joda.time.DateTime;
import org.joda.time.Interval;

public class DateTree {
	private TreeSet<Date> treeset;

	public DateTree() {
		this.treeset = new TreeSet<Date>();
	}

	public void reset() {
		this.treeset = new TreeSet<Date>();
	}

	public void add(Date data) {
		getTreeset().add(data);
	}

	public TreeSet<Date> getTreeset() {
		return treeset;
	}

	public void setTreeset(TreeSet<Date> treeset) {
		this.treeset = treeset;
	}

	public Date nearest(Date data) {
		DateTime dataF = new DateTime(data);

		Date dataMin = getTreeset().lower(data);
		DateTime dataMinJ = new DateTime(dataMin);

		Date dataMax = getTreeset().higher(data);
		DateTime dataMaxJ = new DateTime(dataMax);

		Interval periodMin = new Interval(dataMinJ, dataF);
		Interval periodMax = new Interval(dataF, dataMaxJ);

		if (periodMin.toDurationMillis() < periodMax.toDurationMillis()) {
			return dataMin;
		} else {
			return dataMax;
		}
	}

	public static void main(String[] args) throws ParseException {
		SimpleDateFormat form = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
		DateTree dat = new DateTree();
		dat.add(form.parse("01-01-2011 10:30:00"));
		dat.add(form.parse("01-01-2011 10:50:00"));
		dat.add(form.parse("01-01-2011 11:00:00"));

		Date result = dat.nearest(form.parse("01-01-2011 10:56:00"));
		System.out.println(result);
	}
}
